import axios from "axios";

import router from "@/router";

import { ElLoading } from "element-plus";
import { ElMessage } from "element-plus";

const contentTypeForm = "application/x-www-form-urlencoded;charset=UTF-8";
const contentTypeJson = "application/json";
const contentTypeFile = "multipart/form-data";

const request = (config) => {
  let { url, params, dataType = "form", showLoading = "true" } = config;

  let contentType = contentTypeForm;
  if (dataType === "json") {
    contentType = contentTypeJson;
  } else if (dataType === "file") {
    // console.log(params);
    contentType = contentTypeFile;
    let param = new FormData();
    for (let key in params) {
      param.append(key, params[key]);
    }
    params = param;
    // for (let pair of param.entries()) {
    //   console.log(pair[0] + ': ' + pair[1]);
    // }
  }

  const instance = axios.create({
    baseURL: "/api",
    timeout: 10 * 1000,
    headers: {
      "Content-Type": contentType,
      "X-Requested-With": "XMLHttpRequest",
    },
  });

  let loading = null;
  instance.interceptors.request.use(
    (config) => {
      if (showLoading) {
        loading = ElLoading.service({
          lock: true,
          text: "加载中...",
          background: "rgba(0, 0, 0, 0.7)",
        });
      }
      return config;
    },
    (error) => {
      if (showLoading && loading) {
        loading.close();
      }
      ElMessage.error("发送请求失败.");
      return Promise.reject("发送请求失败");
    }
  );

  // 请求后拦截
  instance.interceptors.response.use(
    (response) => {
      if (showLoading && loading) {
        loading.close();
      }
      const responseData = response.data;
      // console.log(responseData.info)
      if (responseData.status == "error") {
        if (config.errorCallback) {
          config.errorCallback();
        }
        // console.log(responseData.info);
        return Promise.reject(responseData.info);
      } else {
        if (responseData.code == 200) {
          // ElMessage.success("Success");
          return responseData;
        } else if (responseData.code == 901) {
          setTimeout(() => {
            router.push("./login");
          }, 2000);
          return Promise.reject("登录超时");
        }
      }
    },
    (error) => {
      if (showLoading && loading) {
        loading.close();
      }
      return Promise.reject("网络异常");
    }
  );

  return instance.post(url, params).catch((error) => {
    ElMessage.error(error + "123");
    return null;
  });

  // let result = new Promise((resolve, reject) => {
  //   instance
  //     .post(url, params)
  //     .then((res) => {
  //       resolve(res);
  //     })
  //     .catch((error) => {
  //       // console.log("result")
  //       ElMessage.error(error);
  //       // ElMessage.warning(error);
  //     });
  // });

  // return result;
};

export default request;
